package com.kit.data.kitopeso.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.IntentSenderRequest;
import androidx.activity.result.contract.ActivityResultContracts;

import com.google.android.gms.auth.api.identity.GetPhoneNumberHintIntentRequest;
import com.google.android.gms.auth.api.identity.Identity;
import com.google.gson.JsonObject;
import com.kit.data.kitopeso.PathMaping;
import com.kit.data.kitopeso.R;
import com.kit.data.kitopeso.analysis.AnalysisUtil;
import com.kit.data.kitopeso.base.BaseActivity;
import com.kit.data.kitopeso.base.BaseDialog;
import com.kit.data.kitopeso.base.BaseParams;
import com.kit.data.kitopeso.databinding.KitoLoginActivityBinding;
import com.kit.data.kitopeso.net.PU;
import com.kit.data.kitopeso.net.RxHttp;
import com.kit.data.kitopeso.net.U;
import com.kit.data.kitopeso.obj.KitoLogin;
import com.kit.data.kitopeso.tools.AESCryptUtilJar;
import com.kit.data.kitopeso.tools.JsonParse;
import com.kit.data.kitopeso.tools.LogUtil;
import com.kit.data.kitopeso.tools.PhoneUtils;
import com.kit.data.kitopeso.tools.ResUtils;
import com.kit.data.kitopeso.tools.SpUtils;
import com.kit.data.kitopeso.tools.Tools;
import com.kit.data.kitopeso.tools.ViewUtils;
import com.kit.data.kitopeso.view.KitoURLSpan;

import java.util.HashMap;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class KitoLoginActivity extends BaseActivity<KitoLoginActivityBinding> {


    GetPhoneNumberHintIntentRequest request;

    private final int TIME_WHAT = 1;

    boolean isShow;

    @Override
    protected KitoLoginActivityBinding initViewBinding(LayoutInflater inflater) {
        return KitoLoginActivityBinding.inflate(inflater);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initView() {

        SpannableString spannableString = getSpannableString();
        if (U.URL_MOBILE_CODE.contains("+")) {
            binding.tvCode.setText(U.URL_MOBILE_CODE);
        } else {
            binding.tvCode.setText("+" + U.URL_MOBILE_CODE);
        }
        binding.tvInput.setType(PU.P9);
        binding.boxTxt.setText(spannableString);
        binding.boxTxt.setMovementMethod(LinkMovementMethod.getInstance());

        request = GetPhoneNumberHintIntentRequest.builder().build();

        binding.tvInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus && !isShow) {
                    isShow=true;
                    binding.tvInput.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            binding.tvInput.setCursorVisible(false);
                            binding.tvInput.clearFocus();
                            binding.tvInput.setInputType(InputType.TYPE_NULL);
                            Tools.hideSoftInputFromWindow(getActivity(), binding.tvInput);
                            showPhoneHit();
                        }
                    },100);
                }
            }
        });

        binding.tvBtn.setOnClickListener(v -> {
            Tools.hideSoftInputFromWindow(getActivity(), binding.tvInput);
            if (binding.tvBtn.isSelected()) {
                ViewUtils.viewScale(v);
                boolean isChecked = binding.tvBox.isChecked();
                if (isChecked) {
                    toLogin();
                } else {
                    showDialog();
                }
            }
        });
        binding.tvInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                switchState(false);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        binding.getRoot().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Tools.hideSoftInputFromWindow(getActivity(), binding.getRoot());
            }
        });
        binding.tvRoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Tools.hideSoftInputFromWindow(getActivity(), binding.tvRoot);
            }
        });

        binding.tvCs.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            startActivity(new Intent(getActivity(), KitoCustomerServiceActivity.class));
        });

    }

    @Override
    protected void initData() {
        UP_TYPE1 = PU.P7;
        UP_TYPE2 = PU.P8;
    }

    void showPhoneHit() {
        isShow = true;
        Identity.getSignInClient(this)
                .getPhoneNumberHintIntent(request)
                .addOnSuccessListener(result -> {
                    try {
                        IntentSenderRequest request1 = new IntentSenderRequest.Builder(result.getIntentSender()).build();
                        phoneNumberHintLauncher.launch(request1);
                    } catch (Exception e) {
                        LogUtil.e("me", "Launching the PendingIntent failed->" + e);
                    } finally {
                        LogUtil.e("me", "<-registerForActivityResult->");
                        showInput();
                    }
                })
                .addOnFailureListener(e -> {
                    LogUtil.e("me", "Phone Number Hint failed->" + e);
                    showInput();
                });
    }

    void showInput() {
        binding.tvInput.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.tvInput.setCursorVisible(true);
//        binding.tvInput.requestFocus();
        String data = binding.tvInput.getText().toString();
        if (!TextUtils.isEmpty(data)) {
            binding.tvInput.setSelection(data.length());
        }
        Tools.showKeyboard(binding.tvInput);
    }

    final ActivityResultLauncher<IntentSenderRequest> phoneNumberHintLauncher =
            registerForActivityResult(new ActivityResultContracts.StartIntentSenderForResult(),
                    result -> {
                        try {
                            String phoneNumber = Identity.getSignInClient(getActivity())
                                    .getPhoneNumberFromIntent(result.getData());
                            LogUtil.e("me", "PhoneNumber->" + phoneNumber);
                            if (!TextUtils.isEmpty(phoneNumber)) {
                                binding.tvInput.setText(PhoneUtils.extractLocalNumber(phoneNumber));
                                binding.tvInput.setSelection(binding.tvInput.length());
                            }
                        } catch (Exception e) {
                            LogUtil.e("me", "Failed to retrieve number->" + e);
                        }
                    });

    SpannableString getSpannableString() {
        SpannableString spannableString = new SpannableString(getResources().getString(R.string.login_privacy));

        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor(("#813FF8")));


        KitoURLSpan myURLSpan = new KitoURLSpan();
        myURLSpan.setOnClickableSpanInterface(view -> startActivity(new Intent(getActivity(), KitoPrivacyActivity.class)));
        spannableString.setSpan(myURLSpan, 10, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        spannableString.setSpan(colorSpan, 10, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        return spannableString;
    }

    void showDialog() {
        showTipsDialog("", "", "", ResUtils.s(R.string.login_privacy_tips), false, new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {
                binding.tvBox.setChecked(true);
                toLogin();
            }

            @Override
            public void btnOnClickCancel() {

            }

            @Override
            public void btnOnClickColse() {

            }
        });
    }

    void switchState(boolean isError) {
        if (isError) {
            binding.tvHit.setVisibility(View.VISIBLE);
            binding.tvHit.setText(getResources().getString(R.string.login_e_hit));
            binding.tvBtn.setSelected(false);
            binding.tvInput.setSelected(true);
            binding.inputLayout.setSelected(true);
        } else {
            binding.tvHit.setVisibility(View.GONE);
            String phoneNumber = binding.tvInput.getText().toString();
            binding.tvBtn.setSelected(!TextUtils.isEmpty(phoneNumber));
            binding.tvInput.setSelected(false);
            binding.inputLayout.setSelected(false);
        }
    }

    void toLogin() {
        String phoneNumber = binding.tvInput.getText().toString();
        if (!PhoneUtils.isPhoneNumber(phoneNumber)) {
            switchState(true);
            return;
        }
        String token = PhoneUtils.isAccM(phoneNumber);
        PU.userBuriedPoint(PU.P10, U.URL_MOBILE_CODE + "##" + phoneNumber);
        PU.userBuriedAllPoint(getActivity());
        if (!TextUtils.isEmpty(token)) {
            showLoading("");
            mHandler.sendEmptyMessageDelayed(TIME_WHAT, 2000);
        } else {
            userLoginNoCode(phoneNumber);
        }
    }

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@androidx.annotation.NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == TIME_WHAT) {
                if (getActivity() != null && !isFinishing() && !isDestroyed()) {
                    hideLoading();
                    String phoneNumber = binding.tvInput.getText().toString();
                    String token = PhoneUtils.isAccM(phoneNumber);
                    U.URL_PHONE = phoneNumber;
                    SpUtils.save_string(getActivity(), SpUtils.KEY_PHONE, U.URL_PHONE);
                    U.URL_TOKEN = token;
                    SpUtils.save_string(getActivity(), SpUtils.KEY_TOKEN, U.URL_TOKEN);
                    startActivity(new Intent(getActivity(), KitoHomeActivity.class));
                    AnalysisUtil.INSTANCE.initAfterLogin(getApplication());
                    finish();
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeMessages(TIME_WHAT);
            mHandler = null;
        }
    }

    void userLoginNoCode(String phoneNumber) {
        showLoading("");
        String channelCode = AnalysisUtil.INSTANCE.channelCode();
        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[6]);
        json.addProperty("mobile", phoneNumber);
        json.addProperty("code", "0000");
        json.addProperty("channelCode", channelCode);
        json.addProperty("subChannelCode", channelCode);
        json.addProperty("directLoginFlag", "");
        json.addProperty("notBindWalletFlag", "YES");
        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_MAIN_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }
        String data = AESCryptUtilJar.encryptDefault(json.toString());
        LogUtil.e("me", json + "<-userLoginNoCode post->" + data);
        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        hideLoading();
                        if (!TextUtils.isEmpty(s)) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", "userLoginNoCode json->" + json1);
                            if (JsonParse.getCode(json1)) {
                                KitoLogin mLoginBean = JsonParse.userLoginNoCodeJson2Obj(getActivity(), json1);
                                if (mLoginBean != null) {
                                    AnalysisUtil.INSTANCE.initAfterLogin(getApplication());
                                    if (!TextUtils.isEmpty(mLoginBean.getType()) && mLoginBean.getType().equals("REGISTER")) {
                                        AnalysisUtil.INSTANCE.addRegisterEvent();
                                    }
                                    U.URL_PHONE = phoneNumber;
                                    SpUtils.save_string(getActivity(), SpUtils.KEY_PHONE, U.URL_PHONE);
                                    startActivity(new Intent(getActivity(), KitoHomeActivity.class));
                                    finish();
                                } else {
                                    showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                                }
                            } else {
                                showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.login_faile));
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });
    }


}
